//
//  ReplayKit+Clip.swift
//  SwiftCode
//
//  Created by yuhus on 2023/9/21.

import Foundation
import ReplayKit

@available(iOS 15.0, *)
extension ReplayKitExample {
  func clipButtonTapped() {
    // Check the internal recording state.
    if isActive == false {
      // If the recording isn't active, the button starts the clip buffering session.
      startClipBuffering()
    } else {
      // If a recording is active, the button stops the clip buffering session.
      stopClipBuffering()
    }
  }
  
  func generateClipPressed(_ sender: Any) {
    if self.isActive == true && self.getClipButton.isEnabled == true {
      exportClip()
    }
  }
  
  private func startClipBuffering() {
    RPScreenRecorder.shared().startClipBuffering { (error) in
      if error != nil {
        print("Error attempting to start Clip Buffering")
        
        self.setClipState(active: false)
        
      } else {
        // There's no error when attempting to start a clip session. Update the clip state.
        self.setClipState(active: true)
        
        // Set up the camera view.
//        self.setupCameraView()
      }
    }
  }
  
  private func stopClipBuffering() {
    RPScreenRecorder.shared().stopClipBuffering { (error) in
      if error != nil {
        print("Error attempting to stop Clip Buffering")
      }
      // The sample calls this handler when stopClipBuffering finishes. Update the clip state.
      self.setClipState(active: false)
      
      // Tear down the camera view.
      //      self.tearDownCameraView()
    }
  }
  
  private func setClipState(active: Bool) {
    DispatchQueue.main.async {
      if active == true {
        // Set the button title.
        self.clipButton.setTitle("Stop Clip", for: .normal)
      } else {
        // Set the button title.
        self.clipButton.setTitle("Start Clip", for: .normal)
      }
      
      // Set the internal recording state.
      self.isActive = active
      
      // Set the getClip button.
      self.getClipButton.isEnabled = active
      
      // Set the other buttons' isEnabled properties.
      self.recordButton.isEnabled = !active
      self.broadcastButton.isEnabled = !active
      self.captureButton.isEnabled = !active
    }
  }
  
  private func exportClip() {
    let clipURL = getDirectory()
    let interval = TimeInterval(5)
    
    print("Generating clip at URL: ", clipURL)
    RPScreenRecorder.shared().exportClip(to: clipURL, duration: interval) { error in
      if error != nil {
        print("Error attempting to start Clip Buffering")
      } else {
        // There isn't an error, so save the clip at the URL to Photos.
        self.saveToPhotos(tempURL: clipURL)
      }
    }
  }
  
  func getDirectory() -> URL {
    var tempPath = URL(fileURLWithPath: NSTemporaryDirectory())
    let formatter = DateFormatter()
    formatter.dateFormat = "yyyy-MM-dd-hh-mm-ss"
    let stringDate = formatter.string(from: Date())
    print(stringDate)
    tempPath.appendPathComponent(String.localizedStringWithFormat("output-%@.mp4", stringDate))
    return tempPath
  }
  
  func saveToPhotos(tempURL: URL) {
//    PHPhotoLibrary.shared().performChanges {
//      PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: tempURL)
//    } completionHandler: { success, error in
//      if success == true {
//        print("Saved to photos")
//      } else {
//        print("Error exporting clip to Photos")
//      }
//    }
  }
}
